<script lang="ts" setup>
import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
import { isAfter, isEqual } from 'date-fns';
import { onMounted, ref } from 'vue';
import { getHome } from '@/api/home';
import { useLocale } from '@/locale/locale';
import { RouteMap, useRouter } from '@/router';
import { useCheckoutStore } from '@/store/checkout';
import { usePopupStore } from '@/store/popup';
import { useAuthStore } from '@/store/auth';
import { getDefaultAfterDate, getDefaultBeforeDate } from '@/utils/date';
import Recommends from './components/home-recommends.vue';
import Services from './components/home-services.vue';
import Switcher from './components/home-switcher.vue';
import ImageSwitch from './components/image-switch.vue';
import { useUserStore } from '@/store/user';
import { useTitle } from '@/hooks/useTitle';
import { rpx2px } from '@/utils/px';
import { getNavbarHeight } from '@/utils/navbar';

const authStore = useAuthStore();
const checkoutStore = useCheckoutStore();
const userStore = useUserStore();
const { t } = useLocale();
const popupStore = usePopupStore();
const router = useRouter();

onLoad((options) => {
  if (options != undefined) {
    if (options.referrer !== undefined || options.referrer != '') {
      authStore.Setreferrer(options.referrer);
    }
  }
});

onShareAppMessage(() => {
  if (!authStore.isLoggedIn) {
    return {
      title: '您还未登录，登录后分享会获得奖励，是否继续分享！',
      imageUrl: data.value.banners[0]
    };
  }
  return {
    title: '选择住一，带你发现精品民宿，还可享受接送机、按摩、名餐厅代预定服务',
    path: `${RouteMap.home}?referrer=${userStore.user.id}`,
    imageUrl: data.value.banners[0]
  };
});

onShareTimeline(() => {
  return {
    title: '选择住一，带你发现精品民宿，还可享受接送机、按摩、名餐厅代预定服务',
    query: `referrer=${userStore.user.id}`,
    imageUrl: data.value.banners[0]
  };
});

type Language = {
  uuid: string;
  language: string;
  content: string;
};

type Hotel = {
  addressDetail: string;
  cover: string;
  id: number;
  uid: string;
  nameLanguage: Language[];
};

const data = ref<{
  isInitialized: boolean;
  topBg: string;
  banners: string[];
  minDaysNotice: number;
  hotels: Hotel[];
}>({
  isInitialized: false,
  topBg: '',
  banners: [],
  minDaysNotice: 7,
  hotels: []
});

function openPopup(type = 'GuestNumberPicker') {
  if (type === 'GuestNumberPicker') {
    if (checkoutStore.mode === 1) {
      popupStore.openGuestNumberPicker();
    } else {
      popupStore.openBookersNumberPicker();
    }
  } else if (type === 'DatePicker') {
    popupStore.openDatePicker();
  }
}

function updateDate(startDate: string, endDate: string) {
  if (checkoutStore.mode === 2) {
    const addDaysNumber = data.value.minDaysNotice;
    const endDate2 = getDefaultAfterDate(startDate, addDaysNumber);
    if (!isEqual(endDate, endDate2) && isAfter(endDate2, endDate)) {
      return uni.showToast({
        icon: 'none',
        title: t('HomeShortRentDateErrorMsg', { days: addDaysNumber })
      });
    }
  }
  checkoutStore.setDate(startDate, endDate);
  popupStore.closeDatePicker();
  fetchData();
}

function updateMode(mode: 1 | 2) {
  checkoutStore.setMode(mode);
  const startDate = getDefaultBeforeDate();
  const addDaysNumber = mode === 1 ? 1 : data.value.minDaysNotice;
  updateDate(startDate, getDefaultAfterDate(startDate, addDaysNumber));
}

async function fetchData() {
  const res = await getHome();
  if (res.code === 0) {
    const { banner, immovablesCover, min_days_notice, property } = res.data;
    data.value.topBg = immovablesCover;
    data.value.minDaysNotice = min_days_notice;
    data.value.hotels = property.map((item: any) => ({
      addressDetail: item.addressDetail,
      cover: item.cover,
      id: item.id,
      uid: item.uid,
      nameLanguage: item.nameLanguage
    }));

    if (!data.value.isInitialized) {
      data.value.banners = banner.map((item: any) => item.bannerImage);
      data.value.isInitialized = true;
    }
  }
}

onMounted(() => {
  popupStore.init();
  fetchData();
});

const handleLanguageChange = () => {
  data.value.isInitialized = false;
  fetchData();
};

const paddingTop = ref(rpx2px(114));

useTitle(undefined, () => {
  paddingTop.value = paddingTop.value - getNavbarHeight(false);
});
</script>

<template>
  <page-meta :page-style="`overflow: ${popupStore.isHidden ? 'hidden' : 'visible'}`"></page-meta>

  <ImageSwitch :images="data.banners" :is-initialized="data.isInitialized" />

  <!-- 首页logo -->
  <view class="absolute left-0 right-0 px-3" :style="`top: ${paddingTop}px; z-index: 500`">
    <view class="flex justify-between items-center">
      <image src="/static/home_logo.png" style="width: 110px; height: 38px" />
      <apt-language-selector @change="handleLanguageChange" />
    </view>
  </view>

  <!-- 首页内容 -->
  <view
    class="absolute top-0 left-0 right-0 flex flex-col flex-center"
    style="padding-top: 720rpx; z-index: 3"
  >
    <!-- 民宿/短租 -->
    <Switcher
      :active-mode="checkoutStore.mode"
      :days-number="checkoutStore.daysNumber"
      :end-date="checkoutStore.endDate"
      :guest-number="checkoutStore.bookersNumber"
      :start-date="checkoutStore.startDate"
      @open="openPopup"
      @update="updateMode"
    />

    <!-- 广告 -->
    <view
      class="mx-5 mb-2_5 rounded-xl"
      style="width: 670rpx; height: 280rpx"
      @click="router.to(RouteMap.webWeb, { key: 'rental_propagate' })"
    >
      <image :src="data.topBg" class="w-full h-full" />
    </view>
    <!-- 综合服务 -->
    <Services />

    <!-- 推荐 -->
    <Recommends :data="data.hotels" />

    <apt-tab-bar></apt-tab-bar>
  </view>

  <!-- 弹出层 -->
  <apt-date-picker
    :end-date="checkoutStore.endDate"
    :start-date="checkoutStore.startDate"
    @update="updateDate"
  />

  <apt-guest-number-picker
    :adults-number="checkoutStore.adultsNumber"
    :babys-number="checkoutStore.babysNumber"
    :children-number="checkoutStore.childrenNumber"
    @update="checkoutStore.setBookersNumber"
  />

  <apt-bookers-number-picker
    :bookers-number="checkoutStore.bookersNumber"
    @update="checkoutStore.setBookersNumber"
  />
</template>
